#include "StdAfx.h"
#include "RomSet.h"
#include "Rom.h"
//#include "breemlib.h"		//for CInput *input;

static dip_t no_dip[] =
	{
	{"None!",8,0,{{"!",0},{"!",0xFF}}},
	{0,0,0,0,0}	
	};

int CRomSet::AddROM(char *fn,u32 a,u32 s,u32 c,u32 f)
{
Roms.add(new CRom(fn,a,s,c,f,Name));
return(0);
}

int CRomSet::DupROM(u32 a,u32 s)
{
CRom *r = (CRom*)Roms.get(Roms.num() - 1);

if(s == 0)
	s = r->Size;
if(r == 0)
	{
	message("no duplicate\n");
	return(1);
	}
Roms.add(new CRom(r->FileName,a,s,r->CRC,r->Flags,Name));
return(0);
}

CRomSet::CRomSet(char *n)
{
int i;

InitDip();
SetName(n);
HighScoreInfo = 0;
Flags = 0;
for(i=0;i<8;i++)
	Dip[i] = no_dip;
for(i=0;i<MAX_INPUTPORTS;i++)
	InputPorts[i] = 0;
}

CRomSet::~CRomSet()
{
Unload();
}

CRom *CRomSet::GetROM(int idx)
{
return((CRom*)Roms.get(idx));
}

int CRomSet::Num()
{
return(Roms.num());
}

void CRomSet::SetName(char *n)
{
strncpy(Name,n,32);
}

void CRomSet::SetFlags(u32 f)
{
Flags = f;
}

u32 CRomSet::GetFlags()
{
return(Flags);
}

int CRomSet::Load(char *filename)
{
char str[512],*p;
int i;

//sprintf(str,"%s\\%s.zip",strlwr(filename),Name);
sprintf(str,"%s/%s.zip",filename,Name);
if(access(str,04) == 0) //inside zip
	return(LoadZIP(filename));
if((p = strrchr(str,'.')) != 0)						//if there is a dot found...
	{
	if(strncmp(p,".zip",4) == 0)						//it is a zip file
		return(LoadZIP(filename));
	}
message("loading romset from '%s'\n",str);
for(i=0;i<Roms.num();i++)
	{
	CRom *r = (CRom*)Roms.get(i);

	sprintf(str,"%s/%s/%s",settings.romdir,r->Name,r->FileName);
	if(r->Load(str))
		{
		message("error loading '%s'\n",str);
		Unload();
		return(1);
		}
	}
return(0);
}

int CRomSet::LoadZIP(char *filename)
{
char str[512];
int n;

for(n=0;n<Roms.num();n++)
	{
	CRom *r = (CRom*)Roms.get(n);
	
//	sprintf(str,"%s\\%s.zip",strlwr(filename),r->Name);
	sprintf(str,"%s/%s.zip",filename,r->Name);
	if(r->LoadZIP(str) != 0)
		return(1);
	}
message("roms loaded ok from zip file\n");
return(0);
}

void CRomSet::Unload()
{
int i;

for(i=0;i<Roms.num();i++)
	((CRom*)Roms.get(i))->Unload();
}

void CRomSet::InitDip()
{
int n;

for(n=0;n<8;n++)
	Dip[n] = 0;
}

void CRomSet::SetDip(int n,dip_t *d)
{
Dip[n] = d;
}

void CRomSet::SetPort(int n,InputPort *p)
{
InputPorts[n] = p;
}

dip_t *CRomSet::GetDip(int n)
{
return(Dip[n]);
}

InputPort *CRomSet::GetPort(int n)
{
return(InputPorts[n]);
}

void CRomSet::SetHighScoreInfo(highscore_t *h)
{
HighScoreInfo = h;
}

highscore_t *CRomSet::GetHighScoreInfo()
{
return(HighScoreInfo);
}
